package com.kstech.exccheck.view.check;


import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.kstech.exccheck.R;
import com.kstech.exccheck.communication.CommunicationWorker;
import com.kstech.exccheck.config.ConfigFileManager;
import com.kstech.exccheck.config.vo.CheckItemVO;
import com.kstech.exccheck.db.CheckItemDao;
import com.kstech.exccheck.db.CheckItemDetailDao;
import com.kstech.exccheck.db.CheckRecordDao;
import com.kstech.exccheck.domain.check.CheckItemEntity;
import com.kstech.exccheck.domain.check.CheckItemStatusEnum;
import com.kstech.exccheck.domain.check.CheckRecordEntity;
import com.kstech.exccheck.domain.check.CheckRecordStatusEnum;
import com.kstech.exccheck.exception.ExcException;
import com.kstech.exccheck.fragment.DataListFragMent;
import com.kstech.exccheck.fragment.RecyclerDataFragment;
import com.kstech.exccheck.receiver.RealTimeChangedListener;
import com.kstech.exccheck.util.AppContext;
import com.kstech.exccheck.util.DateUtil;
import com.kstech.exccheck.util.DialogUtil;
import com.kstech.exccheck.view.BaseActivity;
import com.kstech.exccheck.receiver.RealTimeParamReceiver;
import com.kstech.exccheck.view.MainActivity;
import com.kstech.exccheck.view.upload.Globals;

import android.widget.AdapterView.OnItemClickListener;
import android.view.View.OnClickListener;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import J1939.J1939_Task;

import static java.lang.Thread.State.TERMINATED;

/**
 * 登陆后的主界面
 */
public class AdminIndexActivity extends BaseActivity implements
        OnClickListener, IntentConstant {
    private DataListFragMent dlf;
    private FragmentTransaction trans;
    // 主页面按钮
    private Button btnCreateCheckRecord, btnOpenCheckRecord, liuchengCheckBtn,
            singleCheckBtn, wholePassBtn, wholeNoPassBtn, wholeForcePassBtn;
    private TextView deviceNameTV, subdeviceNameTV, excIdTV,
            wholeCheckStatusTV, wholeCheckerNameTV, wholeFinishTimeTV,
            wholeSumTimesTV, wholeCheckDescTV;
    private TableRow wholeCheckDescTableRow;

    // 当前机型检查项目列表
    private ListView currentMachineCheckItemList;
    // 检查项目的 适配器和适配器数据
    private CheckItemListAdspter checkItemListAdspter;

    // 当前检验记录
    private CheckRecordEntity checkRecordEntity;

    // listView 选中位置
    private int poisition = -1;

    /**
     * 当前选中的检验项
     */
    private CheckItemEntity checkItemEntity;

    // 实时参数表体
    private TableLayout realTimeParamBody;

    private CheckItemSummaryView currentCheckItemView;

    private RealTimeParamReceiver receiver;

    // 被选中的项目
    private CheckItemLayout selectedItem = null;

    /**
     * The constant j1939ProtTask.
     */
// 1939任务
    public static J1939_Task j1939ProtTask = null;

    /**
     * The constant j1939CommTask.
     */
// 1939任务
    public static CommunicationWorker j1939CommTask = null;

    /**
     * 无用的 file
     */
    Intent clccs = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_index);
//        trans = getFragmentManager().beginTransaction();
//        dlf = new DataListFragMent();
//        trans.replace(R.id.ll_fg_rp,dlf).commit();
        //System.out.println(1/0);
        currentCheckItemView = new CheckItemSummaryView(this);
        // 初始化菜单
        initMenu("");

        // 初始化页面组件
        initViewComp();

        selectedItem = new CheckItemLayout(AppContext.context);

        // 注册广播接收器
        receiver = new RealTimeParamReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction(RealTimeChangedListener.class.getName());
        AdminIndexActivity.this.registerReceiver(receiver,filter);

        // 读取数据库最后一次检测项目的机型信息，首次检测还没有机型，则需要用户新建
        initRecordItem(ConfigFileManager.getInstance().getLastExcid(),
                ConfigFileManager.getInstance().getLastItemid(),true);

        // 初始化监听器
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (checkRecordEntity != null ) {
            initRecordItem(
                    checkRecordEntity.getExcId(),
                    checkItemEntity == null ? null : checkItemEntity
                            .getItemId(),false);
        } else {
            initRecordItem(null, null,false);
        }
    }

    /**
     * 判断当前是否有检验项目被选中
     *
     * @return boolean
     */
    public boolean isCheckItemSelected() {
        return checkRecordEntity != null && checkItemEntity != null;
    }

    /**
     * 初始化页面组件
     */
    private void initViewComp() {
        btnCreateCheckRecord = (Button) findViewById(R.id.btnCreateCheckRecord);
        btnOpenCheckRecord = (Button) findViewById(R.id.btnOpenCheckRecord);
        liuchengCheckBtn = (Button) findViewById(R.id.liuchengCheckBtn);
        singleCheckBtn = (Button) findViewById(R.id.singleCheckBtn);

        deviceNameTV = (TextView) findViewById(R.id.deviceNameTV);
        subdeviceNameTV = (TextView) findViewById(R.id.subdeviceNameTV);
        excIdTV = (TextView) findViewById(R.id.excIdTV);

        currentCheckItemView.initView();
        realTimeParamBody = (TableLayout) findViewById(R.id.realTimeParamBody);

        wholeCheckStatusTV = (TextView) findViewById(R.id.wholeCheckStatusTV);
        wholeCheckerNameTV = (TextView) findViewById(R.id.wholeCheckerNameTV);
        wholeFinishTimeTV = (TextView) findViewById(R.id.wholeFinishTimeTV);
        wholeSumTimesTV = (TextView) findViewById(R.id.wholeSumTimesTV);
        wholeCheckDescTV = (TextView) findViewById(R.id.wholeCheckDescTV);

        wholeCheckDescTableRow = (TableRow) findViewById(R.id.wholeCheckDescTableRow);

        wholePassBtn = (Button) findViewById(R.id.wholePassBtn);
        wholeNoPassBtn = (Button) findViewById(R.id.wholeNoPassBtn);
        wholeForcePassBtn = (Button) findViewById(R.id.wholeForcePassBtn);
        // 如果是检测员，则隐藏强制合格按钮
        if (AppContext.getCurrentUser().getType().getCode().equals("1")) {
            wholeForcePassBtn.setVisibility(View.GONE);
        }
    }

    private void initRecordItem(String excId, String itemId,boolean restartTask) {
        // 初始化的时候excId 为 ""
        if (excId == null || excId.equals("")) {
            clear();
            return;
        }
        LinkedList<String> excIdList = CheckRecordDao.findCheckRecordByUserName(AppContext.getCurrentUser().getName());
        checkRecordEntity = CheckRecordDao.findCheckRecordByExcId(excId);
        if (checkRecordEntity == null) {
            clear();
            return;
        }
        if(!excIdList.contains(excId)){
            clear();
            return;
        }


        // 是否需要停止任务，并重新启动
        if (restartTask) {
            // 初始化记录前，需要加载配置文件，否则，实时参数空指针
            try {
                AppContext.loadDeviceModelFile(checkRecordEntity.getDeviceId(), checkRecordEntity.getSubdeviceId());
            } catch (ExcException e1) {
                Toast.makeText(AppContext.context, e1.getErrorMsg(), Toast.LENGTH_SHORT).show();
                Log.e("AdminIndexActivity", e1.getErrorMsg());
                return;
            }
            // 配置文件加载后需要重新初始化1939任务，任务中包括实时参数的增量初始化
            if (j1939ProtTask != null && j1939ProtTask.isRunning) {
                // 停止通讯任务
                j1939CommTask.setStop(true);
                while (TERMINATED != j1939CommTask.getState()) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                // 停止协议任务
                j1939ProtTask.setStop(true);
                while(TERMINATED != j1939ProtTask.getState()){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            j1939ProtTask = new J1939_Task();
            j1939ProtTask.Init();
            // 启动协议任务
            j1939ProtTask.start();

            // 启动通讯任务
            j1939CommTask = new CommunicationWorker(AppContext.getCurrentCheckLine().getIp(), 4001);
            j1939CommTask.setNetWorkStatusListener(this);
            Log.e("hahah","j1939CommTask start");
            j1939CommTask.start();

        }

        // 按照配置文件，初始化设备通道参数表格
        receiver.initTable(realTimeParamBody);

        List<CheckItemEntity> itemList = CheckItemDao
                .getCheckItemListFromDB(excId);
        checkRecordEntity.setCheckItemList(itemList);

        // 初始化左边检验机型、检验项目信息
        deviceNameTV.setText(checkRecordEntity.getDeviceName());
        subdeviceNameTV.setText(checkRecordEntity.getSubdeviceName());
        excIdTV.setText(checkRecordEntity.getExcId());

        currentMachineCheckItemList = (ListView) findViewById(R.id.currentMachineCheckItemList);
        checkItemListAdspter = new CheckItemListAdspter(this, (ArrayList<CheckItemVO>) AppContext.getModelFile().getCheckItemList());
        currentMachineCheckItemList.setAdapter(checkItemListAdspter);
        currentMachineCheckItemList
                .setOnItemClickListener(checkItemListListener);
        checkItemEntity = checkRecordEntity.getCheckItem(itemId);
        // 默认选中项
        if (checkItemEntity != null) {
            currentMachineCheckItemList.post(new Runnable() {
                @Override
                public void run() {
                    for (int iii = 0; iii < checkRecordEntity
                            .getCheckItemList().size(); iii++) {
                        if (checkRecordEntity.getCheckItemList().get(iii)
                                .getItemId()
                                .equals(checkItemEntity.getItemId())) {
                            // 设置listView滚动条初始位置
                            currentMachineCheckItemList.setSelection(iii);
                            // 设置lieViw默认选中项样式
                            LinearLayout ly = (LinearLayout) currentMachineCheckItemList
                                    .getChildAt(iii);
                            if (ly != null) {
                                selectedItem.setSelected(ly);
                            }
                        }
                    }
                }
            });
            if(AppContext.getModelFile().getCheckItemVO(checkItemEntity.getItemId()) != null ){
                // 初始化检验项目参数列表
                currentCheckItemView.initCheckItemParamList(checkItemEntity);
            }
//          Globals.values = AppContext.getModelFile().getCheckItemVO(checkItemEntity.getItemId()).getParamNameList();
//		    Globals.content = CheckItemDetailDao.getCheckItemDetailList(checkItemEntity.getExcId(), checkItemEntity.getItemId());
        }

        // 初始化整机检验状态
        initWholeCheckStatus(checkRecordEntity);
    }

    private void clear() {
        deviceNameTV.setText("");
        subdeviceNameTV.setText("");
        excIdTV.setText("");
        if (null != currentMachineCheckItemList) {
            currentMachineCheckItemList.setAdapter(null);
        }
        currentCheckItemView.clear();
        wholeCheckStatusTV.setText("");
        wholeCheckerNameTV.setText("");
        wholeFinishTimeTV.setText("");
        wholeSumTimesTV.setText("");
        wholeCheckDescTV.setText("");
        // 清除实时区
        realTimeParamBody.removeAllViews();
    }


    /**
     * Gets selected check item.
     *
     * @return the selected check item
     */
    public CheckItemEntity getSelectedCheckItem() {
        return checkItemEntity;
    }

    /**
     * Gets selected check record.
     *
     * @return the selected check record
     */
    public CheckRecordEntity getSelectedCheckRecord() {
        return checkRecordEntity;
    }

    /**
     * Set poisition.
     *
     * @param position the position
     */
    public void setPoisition(int position){
        this.poisition = position;
    }

    /**
     * Get poisition int.
     *
     * @return the int
     */
    public int getPoisition(){
        return poisition;
    }

    /**
     * listView，检查记录列表点击，监听事件
     */
    OnItemClickListener checkItemListListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                long arg3) {
            LinearLayout ly = (LinearLayout) view;

//			if (selectedItem.isSelected()) {
//				selectedItem.cancelSelected();
//			}
//			selectedItem.setSelected(ly);
            String itemId = ((TextView) ly.getChildAt(0)).getText().toString();
            checkItemEntity = checkRecordEntity.getCheckItem(itemId);

//            Globals.values = AppContext.getModelFile().getCheckItemVO(checkItemEntity.getItemId()).getParamNameList();
//            Globals.content = CheckItemDetailDao.getCheckItemDetailList(checkItemEntity.getExcId(), checkItemEntity.getItemId());
//            dlf.update();
            if(checkItemEntity == null){
                new AlertDialog.Builder(AppContext.context)
                        .setMessage(R.string.xmlAlreadyChanged)
                        .setNeutralButton(R.string.str_ok, null).show();
                return;
            }
            if(AppContext.getModelFile().getCheckItemVO(checkItemEntity.getItemId()) != null ){
                // 加载 项目参数列表
                currentCheckItemView.initCheckItemParamList(checkItemEntity);
                // 保存最后一次点击的 itemID
                ConfigFileManager.getInstance().saveLastItemid(itemId);
            }else {
                new AlertDialog.Builder(AppContext.context)
                        .setMessage(R.string.xmlAlreadyChanged)
                        .setNeutralButton(R.string.str_ok, null).show();
                return;
            }
            poisition = arg2;
            checkItemListAdspter.notifyDataSetChanged();
        }
    };

    /**
     * 初始化整机检验状态
     *
     * @param excId
     * @param cr
     */
    private void initWholeCheckStatus(CheckRecordEntity cr) {
        wholeCheckStatusTV.setText(cr.getCheckStatus());
        wholeCheckerNameTV.setText(cr.getCheckerName());
        wholeFinishTimeTV.setText(cr.getFinishTime() == null ? "无" : cr
                .getFinishTime());
        wholeSumTimesTV.setText(CheckItemDetailDao.getAllTimes(cr.getExcId()) + "次");
        wholeCheckDescTV.setText(cr.getDesc());
    };

    /**
     * 初始化按钮监听器
     */
    public void initListener() {
        btnCreateCheckRecord.setOnClickListener(this);
        btnOpenCheckRecord.setOnClickListener(this);
        liuchengCheckBtn.setOnClickListener(this);
        singleCheckBtn.setOnClickListener(this);

        wholeCheckDescTableRow.setOnClickListener(this);

        wholePassBtn.setOnClickListener(this);
        wholeNoPassBtn.setOnClickListener(this);
        wholeForcePassBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnCreateCheckRecord:
                Intent cintent = new Intent(AdminIndexActivity.this,
                        CreateCheckRecordActivity.class);
                startActivityForResult(cintent, 0);
                break;
            case R.id.btnOpenCheckRecord:
                Intent ointent = new Intent(AdminIndexActivity.this,
                        OpenCheckRecordActivity.class);
                startActivityForResult(ointent, 1);
                break;
            case R.id.liuchengCheckBtn:
                checkButHandle("liucheng");
                break;
            case R.id.singleCheckBtn:
                checkButHandle("single");
                break;
            case R.id.wholeCheckDescTableRow:
                if (null == checkRecordEntity) {
                    return;
                }
                // 初始化检验说明弹出菜单
                LayoutInflater layoutInflater = (LayoutInflater) this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                final View layout = layoutInflater.inflate(
                        R.layout.activity_admin_index_whole_check_desc, null);
                final PopupWindow changeStatusPopUp = new PopupWindow(this);
                changeStatusPopUp.setContentView(layout);
                changeStatusPopUp.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
                changeStatusPopUp.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
                changeStatusPopUp.setFocusable(true);
                // changeStatusPopUp.setBackgroundDrawable(getDrawable(R.drawable.rect_gray));
                changeStatusPopUp.setBackgroundDrawable(null);
                changeStatusPopUp.showAtLocation(layout, Gravity.TOP, 0, 100);

                Button saveCheckDescBtn = (Button) layout
                        .findViewById(R.id.saveCheckDescBtn);
                Button closeCheckDescBtn = (Button) layout
                        .findViewById(R.id.closeCheckDescBtn);
                final EditText checkDescET = (EditText) layout
                        .findViewById(R.id.checkDescET);
                checkDescET.setText(CheckRecordDao.findCheckRecordByExcId(
                        excIdTV.getText().toString()).getDesc());
                saveCheckDescBtn.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        CheckRecordDao.updateCheckDesc(
                                excIdTV.getText().toString(), checkDescET.getText()
                                        .toString());
                        wholeCheckDescTV.setText(checkDescET.getText().toString());
                        changeStatusPopUp.dismiss();
                    }
                });
                closeCheckDescBtn.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        changeStatusPopUp.dismiss();
                    }
                });
                break;
            case R.id.wholePassBtn:
                if("未完成".equals(checkRecordEntity.getCheckStatus())){

                    //未检测 或 未完成 无法合格
                    List<CheckItemEntity> itemList = checkRecordEntity.getCheckItemList();
                    for (CheckItemEntity item : itemList) {
                        String status = item.getCheckStatus();
                        if ((status.equals(CheckItemStatusEnum.UN_CHECK.getCode()) || status.equals(CheckItemStatusEnum.UN_FINISH.getCode())) && !item.getCheckDesc().contains("ignore$")) {
                            new AlertDialog.Builder(AppContext.context)
                                    .setMessage(R.string.recordNotFinish)
                                    .setNeutralButton(R.string.str_ok, null).show();
                            return;
                        }
                    }
                    new AlertDialog.Builder(AppContext.context)
                            .setTitle(R.string.diaLogWakeup)
                            .setMessage(R.string.passConfirm)
                            .setNegativeButton(R.string.str_close, null)
                            .setPositiveButton(R.string.str_ok,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            updateWholeArea(CheckRecordStatusEnum.PASS.getCode(),CheckRecordStatusEnum.PASS.getName());
                                            checkRecordEntity.setCheckStatus(CheckRecordStatusEnum.PASS.getName());
                                        }
                                    }).show();

                    return;
                }else {
                    new AlertDialog.Builder(AppContext.context)
                            .setMessage(R.string.recordAlreadyFinish)
                            .setNeutralButton(R.string.str_ok, null).show();
                }
                break;
            case R.id.wholeNoPassBtn:
                Log.e("CB",checkRecordEntity.getCheckStatus());
                if("未完成".equals(checkRecordEntity.getCheckStatus())){

                    //未检测 或 未完成 无法合格
                    List<CheckItemEntity> itemList = checkRecordEntity.getCheckItemList();
                    for (CheckItemEntity item : itemList) {
                        String status = item.getCheckStatus();
                        if ((status.equals(CheckItemStatusEnum.UN_CHECK.getCode()) || status.equals(CheckItemStatusEnum.UN_FINISH.getCode())) && !item.getCheckDesc().contains("ignore$")) {
                            new AlertDialog.Builder(AppContext.context)
                                    .setMessage(R.string.recordNotFinish)
                                    .setNeutralButton(R.string.str_ok, null).show();
                            return;
                        }
                    }
                    new AlertDialog.Builder(AppContext.context)
                            .setTitle(R.string.diaLogWakeup)
                            .setMessage(R.string.unpassConfirm)
                            .setNegativeButton(R.string.str_close, null)
                            .setPositiveButton(R.string.str_ok,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            updateWholeArea(CheckRecordStatusEnum.UN_PASS.getCode(), CheckRecordStatusEnum.UN_PASS.getName());
                                            checkRecordEntity.setCheckStatus(CheckRecordStatusEnum.UN_PASS.getName());
                                        }
                                    }).show();

                    return;
                }else {
                    new AlertDialog.Builder(AppContext.context)
                            .setMessage(R.string.recordAlreadyFinish)
                            .setNeutralButton(R.string.str_ok, null).show();
                }
                break;
            case R.id.wholeForcePassBtn:
                if("未完成".equals(checkRecordEntity.getCheckStatus())){
                    Log.e("CB",""+checkRecordEntity.getCheckStatus());
                    //未检测 或 未完成 无法合格
                    List<CheckItemEntity> itemList = checkRecordEntity.getCheckItemList();
                    for (CheckItemEntity item : itemList) {
                        String status = item.getCheckStatus();
                        if ((status.equals(CheckItemStatusEnum.UN_CHECK.getCode()) || status.equals(CheckItemStatusEnum.UN_FINISH.getCode())) && !item.getCheckDesc().contains("ignore$")) {
                            new AlertDialog.Builder(AppContext.context)
                                    .setMessage(R.string.recordNotFinish)
                                    .setNeutralButton(R.string.str_ok, null).show();
                            return;
                        }
                    }
                    new AlertDialog.Builder(AppContext.context)
                            .setTitle(R.string.diaLogWakeup)
                            .setMessage(R.string.forcepassConfirm)
                            .setNegativeButton(R.string.str_close, null)
                            .setPositiveButton(R.string.str_ok,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            updateWholeArea(CheckRecordStatusEnum.FORCE_PASS.getCode(), CheckRecordStatusEnum.FORCE_PASS.getName());
                                            checkRecordEntity.setCheckStatus(CheckRecordStatusEnum.FORCE_PASS.getName());
                                        }
                                    }).show();

                    return;
                }else if("合格".equals(checkRecordEntity.getCheckStatus()) || "强制合格".equals(checkRecordEntity.getCheckStatus())){
                        Log.e("CB","else"+checkRecordEntity.getCheckStatus());
                        new AlertDialog.Builder(AppContext.context)
                                .setMessage(R.string.recordAlreadyhegeFinish)
                                .setNeutralButton(R.string.str_ok, null).show();
                } else if("未合格".equals(checkRecordEntity.getCheckStatus())){
                    new AlertDialog.Builder(AppContext.context)
                            .setTitle(R.string.diaLogWakeup)
                            .setMessage(R.string.forcepassConfirm)
                            .setNegativeButton(R.string.str_close, null)
                            .setPositiveButton(R.string.str_ok,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            updateWholeArea(CheckRecordStatusEnum.FORCE_PASS.getCode(), CheckRecordStatusEnum.FORCE_PASS.getName());
                                            checkRecordEntity.setCheckStatus(CheckRecordStatusEnum.FORCE_PASS.getName());
                                        }
                                    }).show();
                }


                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (null != data) {
            // 新建或打开回调
            if (requestCode == 0 || requestCode == 1) {
                // 删除所有参数数据，等待重新点击项目加载
                poisition = -1;
                currentCheckItemView.clear();
                String excId = data.getStringExtra("excId");
                initRecordItem(excId, null, true);
                // 保存新建或打开的最后一次挖掘机出厂编号
                ConfigFileManager.getInstance().saveLastExcid(excId);
                ConfigFileManager.getInstance().saveLastItemid("");
            }
        } else if (requestCode == 2){
            // 单项检测回调，更新左侧当前检验项目的下标
            initRecordItem(checkRecordEntity.getExcId(), ConfigFileManager.getInstance().getLastItemid(), false);
        }
    }

    /**
     * 更新整机显示区域内容，更新数据库
     *
     * @param stateCode the state code
     * @param stateName the state name
     */
    public void updateWholeArea(String stateCode,String stateName){
        if (checkRecordEntity!=null) {
            String finishTime = DateUtil.getCurrentEndMin();
            CheckRecordDao.updateCheckStatus(checkRecordEntity.getExcId(), stateCode,finishTime);
            wholeCheckStatusTV.setText(stateName);
            wholeCheckerNameTV.setText(AppContext.getCurrentUser().getName());
            wholeFinishTimeTV.setText(finishTime);
        }
    }

    /**
     * 单项检测，流程检测，处理
     * @param checkBtnName
     */
    private void checkButHandle(String checkBtnName){
        String ssid = "";
        WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiinfo = manager.getConnectionInfo();
        if(wifiinfo!=null){
            ssid = wifiinfo.getSSID();
            Log.e("LOGIN","---S S I D---"+ssid);
        }
        if(!ssid.equals("\""+ConfigFileManager.getInstance().getLastSsid()+"\"")){
            Log.e("LOGIN","---L O C A L  S S I D---"+ConfigFileManager.getInstance().getLastSsid());
            new AlertDialog.Builder(AdminIndexActivity.this)
                    .setMessage(R.string.checkLineError)
                    .setNeutralButton(R.string.str_ok, null).show();
            return;
        }else {
            Log.e("LOGIN","---L O C A L  S S I D---"+ConfigFileManager.getInstance().getLastSsid());
        }
        if("数据上传".equals(AppContext.getCurrentCheckLine().getName())){
            new AlertDialog.Builder(AdminIndexActivity.this)
                    .setMessage(R.string.checkByUploadError)
                    .setNeutralButton(R.string.str_ok, null).show();
            return;
        }
        if (!isCheckItemSelected()) {
            new AlertDialog.Builder(this)
                    .setMessage(R.string.please_selectOne_check_item)
                    .setNeutralButton(R.string.str_ok, null).show();
            return;
        }
        Intent sintent = new Intent(AdminIndexActivity.this,
                SingleCheckActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(CHECK_ITEM, checkItemEntity);
        bundle.putSerializable(CHECK_RECORD, checkRecordEntity);
        sintent.putExtras(bundle);
        sintent.putExtra(DEVICE_NAME, checkRecordEntity.getDeviceName());
        sintent.putExtra(SUB_DEVICE_NAME,
                checkRecordEntity.getSubdeviceName());
        sintent.putExtra(EXC_ID, checkRecordEntity.getExcId());
        sintent.putExtra(DCHECK_BTN_NAME, checkBtnName);
        startActivityForResult(sintent, 2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止检线状态检查 service
        stopService(clccs);
        // 取消 receiver 注册
        AdminIndexActivity.this.unregisterReceiver(receiver);
        // 停止通讯任务
        j1939CommTask.setStop(true);
        // 停止协议任务
        j1939ProtTask.setStop(true);
    }

}
